﻿using Microsoft.Extensions.Configuration.Json;

namespace JWTWebApi.Utils
{
    /// <summary>
    /// appsettings.json操作类
    /// </summary>
    public class AppSettings
    {

        public static IConfiguration Configuration { get; set; }
        static string contentPath { get; set; }

        public AppSettings(string contentPath)
        {
            string Path = "appsettings.json";

            //如果你把配置文件 是 根据环境变量来分开了，可以这样写
            //Path = $"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json";

            Configuration = new ConfigurationBuilder()
                .SetBasePath(contentPath)
                .Add(new JsonConfigurationSource
                {
                    Path = Path,
                    Optional = false,
                    ReloadOnChange = true
                }) //这样的话，可以直接读目录里的json文件，而不是 bin 文件夹下的，所以不用修改复制属性
                .Build();
        }

        public AppSettings(IConfiguration configuration)
        {
            Configuration = configuration;
        }


        /// <summary>
        /// 获取配置
        /// </summary>
        /// <typeparam name="T">强类型选项类</typeparam>
        /// <param name="path">配置中对应的Key</param>
        /// <returns>TOptions</returns>
        public static T GetConfig<T>(string path)
        {
            if (string.IsNullOrWhiteSpace(path))
            {
                throw new ArgumentException("Path cannot be null or empty", nameof(path));
            }

            try
            {
                var section = Configuration.GetSection(path);
                if (section == null || !section.Exists())
                {
                    throw new KeyNotFoundException($"Configuration section '{path}' not found.");
                }

                T? options = section.Get<T>();
                return options ?? default(T);
            }
            catch (Exception)
            {
                throw;
            }
        }
      
    }
}
